package com.example.myapplication1;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.List;

public class BannerAdapter extends RecyclerView.Adapter<BannerAdapter.BannerViewHolder> {
    // 将成员变量移至Adapter类中
    private List<Banner> mBannerList;
    private Context mContext;
    private OnBannerClickListener mListener;

    // Adapter的构造方法，初始化上下文和数据列表
    public BannerAdapter(Context context, List<Banner> bannerList) {
        mContext = context;
        mBannerList = bannerList;
    }

    @NonNull
    @Override
    public BannerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_banner, parent, false);
        return new BannerViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BannerViewHolder holder, int position) {
        Banner banner = mBannerList.get(position);
        // 使用 Glide 加载网络图片
        Glide.with(mContext)
                .load(banner.getImageUrl())
                .placeholder(R.drawable.placeholder) // 占位图
                .error(R.drawable.error) // 错误图
                .into(holder.ivBanner);

        // 点击事件
        holder.itemView.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onBannerClick(banner.getCourseId());
            }
        });
    }

    @Override
    public int getItemCount() {
        // 避免空指针异常，增加非空判断
        return mBannerList == null ? 0 : mBannerList.size();
    }

    // 正确的ViewHolder定义，只持有视图引用
    public static class BannerViewHolder extends RecyclerView.ViewHolder {
        ImageView ivBanner;

        public BannerViewHolder(@NonNull View itemView) {
            super(itemView);
            ivBanner = itemView.findViewById(R.id.iv_banner);
        }
    }

    // 轮播图点击接口
    public interface OnBannerClickListener {
        void onBannerClick(int courseId);
    }

    public void setOnBannerClickListener(OnBannerClickListener listener) {
        mListener = listener;
    }
}